package controllers

import (
	"fmt"
	"github.com/google/uuid"
	"math/big"
	"photo_credit/constant"
	"photo_credit/eths/credit"
	"photo_credit/models"
	"photo_credit/utils"
	"strconv"
	"strings"
)

type ContentController struct {
	MainController
}

// UploadImage 图片鉴权
func (c *ContentController) UploadImage() {
	f, f2, err := c.GetFile("fileName")
	defer f.Close()
	//获取文件失败
	if err != nil {
		c.APIReturn(20001, "文件上传失败", err)
	}
	//打印文件后缀
	fmt.Println(strings.Split(f2.Filename, ".")[1])
	//读取文件
	buffer := make([]byte, 5000000)
	f.Read(buffer)
	// 根据图片生成UUID
	imageUUID, err := uuid.NewUUID()
	if err != nil {
		fmt.Println(err.Error())
	}
	//图像保存到oss
	imageUrl := utils.UploadImage(buffer, strconv.Itoa(int(imageUUID.ID()))+"."+strings.Split(f2.Filename, ".")[1])
	fmt.Println(imageUrl)

	user := c.GetSession(constant.USER_SESSION)
	loginUser := user.(models.User)
	//图像token，保存到区块链中
	err = credit.Approve(loginUser.IdentityCard, big.NewInt(int64(imageUUID.ID())))
	if err != nil {
		fmt.Println(err)
		c.APIReturn(201, "error", err.Error())
	}
	//oss地址存储到数据库中
	content := models.ContentModel{Title: imageUUID.String(), Url: imageUrl, ContentHash: strconv.Itoa(int(imageUUID.ID())), Price: 0, IdentityCard: loginUser.IdentityCard}
	fmt.Println("****123****")
	err = models.NewContentModel().Add(content)
	if err != nil {
		c.APIReturn(201, "error", err.Error())
	}
	c.APIReturn(200, "success", nil)
}

// ContentList 资产页面
func (c *ContentController) ContentList() {
	user := c.GetSession(constant.USER_SESSION)
	loginUser := user.(models.User)
	list, err := models.NewContentModel().List(loginUser.IdentityCard)
	if err != nil {
		return
	}
	c.Data["list"] = list
	c.TplName = "user-content-list.html"
}

// UpdatePrice 设置价格 todo 未完成
func (c *ContentController) UpdatePrice() {
	price, err2 := c.GetInt("price")
	if err2 != nil {
		return
	}
	fmt.Println(price, "--price")
	//查找作品list
	user := c.GetSession(constant.USER_SESSION)
	loginUser := user.(models.User)
	list, err := models.NewContentModel().List(loginUser.IdentityCard)
	if err != nil {
		return
	}
	c.Data["list"] = list
	c.TplName = "user-content-list.html"
}

// GetAllContent 浏览全部作品
func (c *ContentController) GetAllContent() {
	list, err := models.NewContentModel().GetAllList()
	if err != nil {
		return
	}
	c.Data["list"] = list
	c.TplName = "all-content-list.html"
}

// 购买作品
func (c *ContentController) BuyContent() {
	fromIdCard := c.GetString("from_id_card")
	contentHash := c.GetString("content_hash")
	fmt.Println(fromIdCard, contentHash)
	user := c.GetSession(constant.USER_SESSION)
	loginUser := user.(models.User)
	token, err := strconv.Atoi(contentHash)
	if err != nil {
		return
	}
	err = credit.TransferToken(fromIdCard, loginUser.IdentityCard, big.NewInt(int64(token)))
	if err != nil {
		return
	}

	c.Data["message"] = "购买成功"
	c.TplName = "message.html"
}
